package com.zmx.quartz;


import com.alibaba.fastjson.JSON;
import com.zmx.advice.QuartzException;
import com.zmx.entity.ScheduleJob;
import com.zmx.utils.ContextUtils;
import com.zmx.utils.QuartzConstant;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.lang.reflect.Method;

/**
 * 2020/10/21
 * 15:28
 * zmx
 */
public class MyJob implements Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        // 获取json
        String json = (String) jobDataMap.get(QuartzConstant.DATA_KEY);
        // 解压
        ScheduleJob scheduleJob = JSON.parseObject(json, ScheduleJob.class);
        // 获得类名，方法名与参数
        String beanName = scheduleJob.getBeanName();
        String methodName = scheduleJob.getMethodName();
        // 简单业务一般无参数，复杂业务才有String型参数
        String params = scheduleJob.getParams();
        Object bean = ContextUtils.getBean(beanName);
        try {
            Method method = null;

            if (params == null) {
                method = bean.getClass().getMethod(methodName);
                method.invoke(bean);
            }else {
                method=bean.getClass().getMethod(methodName,String.class);
                // 一般方法都无参数，
                method.invoke(bean,params);
            }
        } catch (Exception e) {
            throw new QuartzException("任务工作调用失败");
        }

    }
}
